<!-- 文件上传，基于 ElUpload 二次封装 -->
<script lang="ts" setup>
import type {
	UploadFile,
	UploadInstance,
	UploadProps,
	UploadRawFile,
	UploadRequestOptions,
	UploadUserFile,
} from "element-plus";
import { genFileId } from "element-plus";

import type { components } from "@/genapi/wh";

import { formatFilePath, uploadRequest } from "./upload-request";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();

type SystemFileDuiXiang = components["schemas"]["SystemFileDuiXiang"];

export interface FileUploadProps {
	modelValue?: SystemFileDuiXiang[];
	limit?: number;
	[x: string]: any;
}

export interface FileUploadEmits {
	(event: "update:modelValue", data?: SystemFileDuiXiang[]): void;
}

defineOptions({ name: "FileUpload", extends: ElUpload });
const props = defineProps<FileUploadProps>();
const emit = defineEmits<FileUploadEmits>();

// id列表
const fileIds = computed(
	() =>
		(props.modelValue?.map((e) => e?.id)?.filter((e) => !!e) as string[]) ?? [],
);

const fileList = ref<UploadUserFile[]>([]);

watchDeep(fileList, (fileList) => {
	emit(
		"update:modelValue",
		fileList
			.filter((e: any) => e.status === "success" && e.response?.id)
			.map((e) => e.response as any),
	);
});

watchArray(
	fileIds,
	(_value, _prev, added, removed) => {
		added.forEach((id) => {
			const index = fileList.value.findIndex((e: any) => e.response?.id === id);
			if (index === -1) {
				const response = props.modelValue?.find((e) => e.id === id);
				response &&
					fileList.value.push({
						name: response.name ?? "",
						url: formatFilePath(response),
						size: response.size,
						percentage: 1,
						status: "success",
						response,
					});
			}
		});
		removed?.forEach((id) => {
			const index = fileList.value.findIndex((e: any) => e.response?.id === id);
			if (index !== -1) {
				fileList.value.splice(index, 1);
			}
		});
	},
	{
		flush: "post",
		immediate: true,
	},
);

const uploadRef = shallowRef<UploadInstance>();

const handleExceed: UploadProps["onExceed"] = (files: any) => {
	if (props.limit === 1) {
		uploadRef.value?.clearFiles?.();
		const file = files[0] as UploadRawFile;
		file.uid = genFileId();
		uploadRef.value?.handleStart(file);
		uploadRef.value?.submit();
	}
};

// async function httpRequest(options: UploadRequestOptions): Promise<any> {
// 	const file = options.file as unknown as File & { uid?: string };
// 	debugger;
//   console.log(file)
//   try {
// 		const { data } = await uploadRequest(file, userStore.imgType, (evt) =>
// 			options.onProgress({ ...evt, percent: evt.total / evt.loaded }),
// 		);
// 		options.onSuccess(data);
// 		return data;
// 	} catch (error: any) {
// 		return options.onError(error);
// 	}
// }
async function httpRequest(options: UploadRequestOptions): Promise<any> {
  console.log(options.file)
	const file = options.file as unknown as File & { uid?: string };
	const type = userStore.imgType;
	try {
		// const { data } = await uploadRequest(options.file, type, (evt) =>
		// 	options.onProgress({ ...evt, percent: evt.total / evt.loaded }),
		// );
    const formData: any = new FormData();
    formData.append("file", options.file);
    const { authorization } = useUserStore();
    const option= {
            headers: {
                    "X-Access-Token": authorization,
            },
    };
    const {data} =await axios.post('/jeecg-boot/dev/file/uploadLocal',formData,option);
		options.onSuccess(data);
    // console.log(options.onSuccess(data))
    // console.log(data)
    ElMessage.success('上传成功')
		return data;
	} catch (error: any) {
    console.log(error)
		return options.onError(error);
	}
}

defineExpose({
	handleRemove: (file: UploadFile) => uploadRef.value?.handleRemove(file),
	handleStart: (rawFile: UploadRawFile) =>
		uploadRef.value?.handleStart(rawFile),
	clearFiles: (status: any) => uploadRef.value?.clearFiles(status),
	submit: () => uploadRef.value?.submit(),
	abort: (file: UploadFile) => uploadRef.value?.abort(file),
	// 判断是否没有正在上传的
	isFinish() {
		return !fileList.value?.find((e) => e.status === "uploading");
	},
});

const vm = getCurrentInstance();

const attrs = computed(() => {
	return {
		...vm?.vnode?.props,
		...props,
		onChange: undefined,
		onRemove: undefined,
	} as any;
});

async function change() {
	await nextTick();

	triggerRef(fileList);
}

function successUpload(response) {
	if (response.fileType === "道路危险货物承运人责任保险") {
		userStore.insuranceId = `${response.location}`.replace(/^\/[^\/]+\//, "/");
	}
}
</script>

<template>
	<ElUpload
		v-bind="attrs"
		ref="uploadRef"
		v-model:file-list="fileList"
		class="upload-demo"
		auto-upload
		:http-request="httpRequest"
		:on-exceed="handleExceed"
		:on-change="change"
		:on-remove="change"
		:limit="1"
		:on-success="successUpload"
	>
		<template v-for="(_item, key) in $slots" #[key]="data">
			<slot v-bind="data" :name="key" />
		</template>
		<!-- <template v-if="!$slots['defualt']">
			<el-icon class="i-ep:plus" text="#D9D9D9! 30px!" />
		</template> -->
		<el-input placeholder="点击上传" style="width: 285px" />
	</ElUpload>
</template>

<style lang="scss">
.file-upload {
	.el-upload-list--picture-card {
		.el-upload-list__item,
		.el-upload--picture-card {
			width: 104px;
			height: 90px;
		}

		&.is-disabled {
			.el-upload--picture-card {
				display: none;
			}
		}
	}
}
</style>
